package com.enqualcomm.kids.component;

import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;

import com.enqualcomm.kids.component.command.BaseCommand;
import com.enqualcomm.kids.component.command.GetPushDataCommand;
import com.enqualcomm.kids.component.command.SendCommand;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.network.socket.request.MessageReceivedParams;
import com.enqualcomm.kids.network.socket.request.UpdatePushNotificationParams;

import java.io.File;
import java.util.concurrent.TimeUnit;

import common.utils.MyLogger;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by yinzhiqun on 2015/10/14.
 */
public class CmdIntentService extends IntentService {

    public static final String REGISTER_PUSH_SERVICE = "100";
    public static final String GET_PUSH_DATA = "200";
    public static final String SOS_RECEIVED = "300";

    private int count;

    public CmdIntentService() {
        super("CmdIntentService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        String action = intent.getAction();
        BaseCommand cmd = null;
        switch (action) {
            case REGISTER_PUSH_SERVICE:
                AppDefault appDefault = new AppDefault();
                cmd = new SendCommand(this, new UpdatePushNotificationParams(appDefault.getUserkey(), appDefault.getUserid(), appDefault.getPushClientId(), 1));
                break;
            case GET_PUSH_DATA:
                if (isFirstTimeOpenApp()) {//是否是第一次打开
                    final BaseCommand getPushDataCommand = new GetPushDataCommand(this);
                    //前40秒，没两秒获取一次。。。
                    Observable.interval(4, TimeUnit.SECONDS).take(19)
                            .filter(new Func1<Long, Boolean>() {
                                private boolean isAppClosed;//目前还是有漏洞，如果退出app小于4秒，还是会重复发送

                                @Override
                                public Boolean call(Long aLong) {
                                    if (isAppClosed) {
                                        return false;
                                    } else {
                                        boolean runningForeground = MyApplication.getInstance().isRunningForeground();
                                        isAppClosed = !runningForeground;
                                        return runningForeground;
                                    }
                                }
                            }).subscribe(new Subscriber<Long>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onNext(Long aLong) {
                            getPushDataCommand.execute();
                        }
                    });
                    return;
                } else {
                    cmd = new GetPushDataCommand(this);
                    break;
                }
            case SOS_RECEIVED:
                String terminalid = intent.getStringExtra("terminalid");
                AppDefault appDefault1 = new AppDefault();
                cmd = new SendCommand(this, new MessageReceivedParams(appDefault1.getUserkey(), appDefault1.getUserid(), terminalid, 14));
                break;
        }

        if (cmd != null) {
            count = 0;
            while (true) {
                int code = cmd.execute();
                if (code == BaseCommand.NO_CONNECTION) {//如果是网络错误，3秒后继续执行
                    if (++count == 5) {
                        break;
                    }
                    SystemClock.sleep(3000);
                } else {//如果是联网成功或者其他类型错误，结束任务
                    break;
                }
            }
        }
    }

    private boolean isFirstTimeOpenApp() {
        File file = new File(getApplicationContext().getFilesDir(), "PushFlag");

        if (file.exists()) {
            file.delete();
            return true;
        } else {
            return false;
        }
    }
}
